package com.wy.wx.controller;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author ：WangYi
 * @date ：Created in 2019/6/13 15:31
 * @description：注意这个controller的注解是@Controller
 * @modified By：
 */
@Controller
@RequestMapping("/wx/oauth")
public class WxOAuthController {
    @Autowired
    private WxMpService wxMpService;
    /**
     * 认证成功后的回调路径，即本对象的userInfo方法
     */
    private static final String OAUTH_SUCCEED_REDIRECT_URL = "http://wxdemo.com/wx/oauth/userInfo";

    @GetMapping("/authorize")
    public String authorize() throws UnsupportedEncodingException {
        /**
         * 该方法构造认证路径
         * 第二个参数是获取用户信息的范围，共有三种范围，详见官方文档（微信）
         */
        final String redirectURL = wxMpService.oauth2buildAuthorizationUrl(OAUTH_SUCCEED_REDIRECT_URL, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode("http://wxdemo.com/index.html", "UTF-8"));
        return "redirect:" + redirectURL;
    }

    /**
     * @param code 十分重要，并且它必须叫code
     * @return
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String state, HttpServletResponse response) throws Exception {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser userInfo = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
        String openId = userInfo.getOpenId();
        //userInfo.getNickname();...可以获取一系列信息
        //这里还可以进行一些业务方法调用
        //将用户信息放在cookie里
        System.out.println("openId = " + openId);
        Cookie cookie = new Cookie("openId", openId);
        cookie.setPath("/");
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
        return "redirect:" + state;
    }
}
